let pollingTimer = null;
let lastSrcs = [];
const scriptReg = /\ <script.*src=["'](?<src>[^"']+)/gm;

// 获取html
const fetchHtml = async () => {
	const res = await fetch('/?_timestamp=' + Date.now(), { cache: 'no-cache' });
	const html = await res.text();
	scriptReg.lastIndex = 0;
	const srcs = [];
	let match;
	while ((match = scriptReg.exec(html))) {
		srcs.push(match.groups.src);
	}
	return srcs;
};

// 比较src和etag
const compareSrcAndEtag = (srcs) => {
	if (!lastSrcs) {
		lastSrcs = srcs;
		return false;
	}
	let flg = false;
	if (srcs.length !== lastSrcs.length) {
		flg = true;
	}
	for (let i = 0; i < srcs.length; i++) {
		if (srcs[i] !== lastSrcs[i]) {
			flg = true;
			break;
		}
	}
	lastSrcs = srcs;
	return flg;
};

// 取消轮询清理
const stopPolling = () => {
	if (pollingTimer) clearTimeout(pollingTimer);
	pollingTimer = null;
};

// 开始轮询
const startPolling = (interval = 5 * 1000) => {
	stopPolling();
	const checkUpdate = async () => {
		const srcs = await fetchHtml();
		const flg = compareSrcAndEtag(srcs);
		if (flg) {
			self.postMessage({ type: 'UPDATE' });
		}
		pollingTimer = setTimeout(checkUpdate, interval);
	};
	checkUpdate();
};

// 监听主线程消息
self.onmessage = (e) => {
	if (e.data.type === 'INIT') {
		const { pollingInterval } = e.data.payload;
		startPolling(Number(pollingInterval) || 5000);
	}
	if (e.data.type === 'TERMINATE') {
		stopPolling();
		self.close(); // 关闭 worker
	}
};
